const fs = require('fs');

// Read the list.json file
fs.readFile('list.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading list.json:', err);
    return;
  }

  // Parse the JSON data
  let jsonData;
  try {
    jsonData = JSON.parse(data);
  } catch (parseErr) {
    console.error('Error parsing JSON:', parseErr);
    return;
  }

  // Encode the data values
  if (jsonData.data && Array.isArray(jsonData.data)) {
    jsonData.data = jsonData.data.map(item => {
      return Object.fromEntries(
        Object.entries(item).map(([key, value]) => {
          if (typeof value === 'string') {
            return [key, encodeURIComponent(value)];
          } else if (Array.isArray(value)) {
            return [key, value.map(v => typeof v === 'string' ? encodeURIComponent(v) : v)];
          } else if (typeof value === 'object' && value !== null) {
            return [key, Object.fromEntries(
              Object.entries(value).map(([k, v]) => [k, typeof v === 'string' ? encodeURIComponent(v) : v])
            )];
          }
          return [key, value];
        })
      );
    });
  }

  // Write the encoded data to final.json
  fs.writeFile('final.json', JSON.stringify(jsonData, null, 2), 'utf8', (writeErr) => {
    if (writeErr) {
      console.error('Error writing final.json:', writeErr);
    } else {
      console.log('Data successfully encoded and written to final.json');
    }
  });
});